import {
  Component,
  Input,
  NgZone,
  ChangeDetectorRef,
  ChangeDetectionStrategy,
  ElementRef,
  ViewChild,
  OnInit,
} from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';
import { format } from 'date-fns';
import { parseDateStr } from '@shared';
import { getTimeDistance } from '@delon/util';
import { zip } from 'rxjs';
import { catchError } from 'rxjs/operators';

/**
 * 全国地图
 */
@Component({
  selector: 'app-prod-china',
  templateUrl: './prod-map.component.html',
  styleUrls: ['./prod-map.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.card]': 'true',
  },
})
export class ProdChinaMapComponent implements OnInit {
  @Input()
  set codeName(val) {
    this._codeName = val;
    const tmp = getTimeDistance('year');
    this.i.start = tmp[0];
    this.i.end = tmp[1];
    this.attachData(this._codeName);
  }
  @Input()
  title = null;
  noData = true;
  noData2 = true;
  _codeName = null;
  data = [];
  trend = [];
  time = null;
  loading = false;
  @ViewChild('ec', { static: true })
  private ec: ElementRef;
  i = { start: null, end: null };
  max = 0;
  min = 0;
  constructor(
    public http: _HttpClient,
    public msg: NzMessageService,
    private ngZone: NgZone,
    private cdr: ChangeDetectorRef,
  ) {}

  geoCoordMap = {};

  render() {
    this.ngZone.runOutsideAngular(() => setTimeout(() => this.init(this.ec.nativeElement), 50));
  }

  ngOnInit() {}

  resetData() {
    this.data = [
      { name: '北京', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '天津', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '河北', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '山西', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '内蒙古', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '辽宁', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '吉林', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '黑龙江', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '上海', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '江苏', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '浙江', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '安徽', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '福建', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '江西', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '山东', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '河南', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '湖北', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '湖南', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '重庆', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '四川', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '贵州', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '云南', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '西藏', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '陕西', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '甘肃', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '青海', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '宁夏', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '新疆', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '广东', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '广西', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '海南', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '台湾', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '香港', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '澳门', value: 0, pf: 0, ls: 0, ds: 0 },
      { name: '南海诸岛', value: 0, pf: 0, ls: 0, ds: 0 },
    ];
  }

  private attachData(codeName) {
    const { ngZone } = this;
    ngZone.run(() => {
      this.loading = true;
      this.cdr.detectChanges();
    });

    const endDate = format(this.i.end, 'YYYY-MM-DD');
    const startDate = format(this.i.start, 'YYYY-MM-DD');
    const apis = [
      this.http.post(`/cf/report/prod/salechina/${codeName}`, { startDate, endDate }),
      this.http.post(`/cf/report/prod/saletrend/${codeName}`, { startDate, endDate }),
    ];
    zip(...apis)
      .pipe(
        catchError(([china, trend]) => {
          return [china, trend];
        }),
      )
      .subscribe(([china, trend]) => {
        ngZone.run(() => {
          // 地图数据start
          this.max = 0;
          this.min = 0;
          this.noData = true;
          this.noData2 = true;
          this.resetData();
          this.trend = [];
          if (china.data && china.data.length > 0) {
            this.noData = false;
            china.data.forEach(r => {
              const dataRow = this.data.filter(d => d.name === r.NAME)[0];
              dataRow.value = r.SC;
              dataRow.pf = r.PF;
              dataRow.ls = r.LS;
              dataRow.ds = r.DS;
              if (r.SC > this.max) {
                this.max = r.SC;
              }
              if (r.SC < this.min) {
                this.min = r.SC;
              }
            });
            this.data = this.data.sort((a, b) => {
              return b.value - a.value;
            });
            this.render();
          } else {
            this.noData = true;
          }
          // 地图数据end
          // 趋势数据start
          if (trend.data && trend.data.length > 0) {
            this.noData2 = false;
            trend.data.forEach(r => {
              this.trend.push({ x: r.MONTH, y: r.SC });
            });
          } else {
            this.noData2 = true;
          }
          // 趋势数据end

          this.time = new Date();
          this.loading = false;
          this.cdr.detectChanges();
        });
      });
  }

  private init(container: HTMLElement) {
    const { geoCoordMap, data } = this;
    const myChart = echarts.init(container);
    const mapFeatures = echarts.getMap('china').geoJson.features;
    mapFeatures.forEach(v => {
      // 地区名称
      const name = v.properties.name;
      // 地区经纬度
      geoCoordMap[name] = v.properties.cp;
    });
    const option = {
      tooltip: {
        padding: 0,
        enterable: true,
        transitionDuration: 1,
        textStyle: {
          color: '#000',
          decoration: 'none',
        },
        formatter: params => {
          let isLot = false;
          if (params.value instanceof Array) {
            isLot = true;
          }
          let tipHtml = '';
          tipHtml =
            '<div style="width:180px;border-radius: 5px;height:140px;background:rgba(255,255,255, 0);border:1px solid #4a4a4a;">' +
            '<div style="width:100%;height:40px;line-height:40px;">' +
            '<span style="margin-left:10px;color:white;font-size:16px;">' +
            params.name +
            '</span>' +
            '</div>' +
            '<div style="padding:5px">' +
            '<div style="color:white;font-size:12px;">' +
            '合计：' +
            '<span style="margin:0 6px;">' +
            (isLot ? params.data.other.value : params.value) +
            '</span></div>' +
            '<div style="color:white;font-size:12px;">' +
            '批发：' +
            '<span style="margin:0 6px;">' +
            (isLot ? params.data.other.pf : params.data.pf) +
            '</span></div>' +
            '<div style="color:white;font-size:12px;">' +
            '电商：' +
            '<span style="margin:0 6px;">' +
            (isLot ? params.data.other.ds : params.data.ds) +
            '</span></div>' +
            '<div style="color:white;font-size:12px;">' +
            '零售：' +
            '<span style="margin:0 6px;">' +
            (isLot ? params.data.other.ls : params.data.ls) +
            '</span></div>' +
            '</div>' +
            '</div>';
          return tipHtml;
        },
      },

      visualMap: {
        show: true,
        min: this.min,
        max: this.max,
        left: '10%',
        top: 'bottom',
        calculable: true,
        seriesIndex: [1],
        inRange: {
          color: ['#fff', '#04387b'], // 蓝绿
        },
      },
      geo: {
        show: true,
        map: 'china',
        label: {
          normal: {
            show: false,
          },
          emphasis: {
            show: false,
          },
        },
        roam: false,
        itemStyle: {
          normal: {
            areaColor: '#023677',
            borderColor: '#1180c7',
          },
          emphasis: {
            areaColor: '#7ca8b9',
          },
        },
      },
      series: [
        {
          name: '散点',
          type: 'scatter',
          coordinateSystem: 'geo',
          data: this.convertData(data),
          symbolSize: val => {
            return this.max < 10 ? val[2] * 2 : val[2] / 2;
          },
          label: {
            normal: {
              formatter: '{b}',
              position: 'right',
              show: true,
            },
            emphasis: {
              show: true,
            },
          },
          itemStyle: {
            normal: {
              color: '#fff',
            },
          },
        },
        {
          type: 'map',
          map: 'china',
          geoIndex: 0,
          aspectScale: 0.75, // 长宽比
          showLegendSymbol: false, // 存在legend时显示
          label: {
            normal: {
              show: true,
            },
            emphasis: {
              show: false,
              textStyle: {
                color: '#fff',
              },
            },
          },
          roam: true,
          itemStyle: {
            normal: {
              areaColor: '#031525',
              borderColor: '#3B5077',
            },
            emphasis: {
              areaColor: '#2B91B7',
            },
          },
          animation: false,
          data: this.data,
        },
        {
          name: '点',
          type: 'scatter',
          coordinateSystem: 'geo',
          zlevel: 6,
        },
        {
          name: 'Top 10',
          type: 'effectScatter',
          coordinateSystem: 'geo',
          data: this.convertData(
            this.data
              .sort((a, b) => {
                return b.value - a.value;
              })
              .slice(0, 10),
          ),
          symbolSize: val => {
            return this.max < 10 ? val[2] * 2 : val[2] / 2;
          },
          showEffectOn: 'render',
          rippleEffect: {
            brushType: 'stroke',
          },
          hoverAnimation: true,
          label: {
            normal: {
              formatter: '{b}',
              position: 'left',
              show: false,
            },
          },
          itemStyle: {
            normal: {
              color: '#f3ea7e',
              shadowBlur: 10,
              shadowColor: 'white',
            },
          },
          zlevel: 1,
        },
      ],
    };
    myChart.setOption(option);
    this.cdr.detectChanges();
  }

  convertData = data => {
    const res = [];
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < data.length; i++) {
      const geoCoord = this.geoCoordMap[data[i].name];
      if (geoCoord) {
        res.push({
          name: data[i].name,
          value: geoCoord.concat(data[i].value),
          other: data[i],
        });
      }
    }
    return res;
  };

  /**
   * 日期变更
   */
  onDateChange(v) {
    if (!v) {
      this.attachData(this._codeName);
    }
  }
}
